<?php

class Application_Model_Post extends Zend_Db_Table_Abstract {
	
		protected $_name = 'post';
		
		public function fetchAlldataOrderById()
		{
			$select = $this->select();
			$select->setIntegrityCheck(false)
				   ->from($this)
				   ->joinUsing('langue','LANGUE_ID')
				   ->order(array('post_id DESC'));
			return $this->fetchAll($select);
		}
		
		public function fetchLimitPostOrderById($count, $offset)
		{
			$select = $this->select();
			$select	->setIntegrityCheck(false)
					->from($this)
					->order(array('post_id DESC'))
					->limit($count, $offset);
			return $this->fetchAll($select);
		}
		
		public function fetchByValeur($count, $offset,$valeur)
		{
			$select = $this->select();
			$select	->setIntegrityCheck(false)
					->from($this)
					->orWhere('POST_TITRE LIKE ?', '%'.$valeur.'%')
					->orWhere('POST_DESCRIPTION LIKE ?', '%'.$valeur.'%')
					->order(array('post_id DESC'))
					->limit($count, $offset);
			return $this->fetchAll($select);
		}
		
		public function countAllPost($valeur)
		{
			$select = $this->select();
			$select->setIntegrityCheck(false)
				->from($this, array('count' => 'COUNT(*)'))
				->orWhere('POST_TITRE LIKE ?', '%'.$valeur.'%')
				->orWhere('POST_DESCRIPTION LIKE ?', '%'.$valeur.'%');
			return $this->fetchrow($select);
		}
		
		public function addPost($params) {
		 $post = $this->createRow(array(
            'USER_ID' => $params['user'],
            'POST_TITRE' => $params['titre'],
			'POST_DESCRIPTION' => $params['description'],
			'POST_DATE' => $params['date'],
			'POST_PHOTO' => $params['photo'],
		 	'LANGUE_ID' => $params['langue']));
				
			$post->save();
		}
		
		 public function editPost($idpost,$params) {
		  $where = $this->getAdapter()->quoteInto('post_id = ?', $idpost);
		  $data = array (
		  'USER_ID' => $params['user'],
          'POST_TITRE' => $params['titre'],
		  'POST_DESCRIPTION' => $params['description'],
		  'POST_PHOTO' => $params['photo'],
	      'POST_DATE' => $params['date'],
		  'LANGUE_ID' => $params['langue']);
		  $this->update($data, $where);
		}
		
		public function deletePost($idpost) {
		    $where = $this->getAdapter()->quoteInto('post_id = ?', $idpost);
			$post = $this->fetchRow($where);
			$photo = $post->POST_PHOTO;
		  
		   //Si la photo existe on l'a supprime
		   if(file_exists(PUBLIC_PATH.'/'.$photo))
		   {	
		   		$filename = PUBLIC_PATH.'/'.$photo;
		   	
		   		//On nous attribuant tous les droits au fichier
		  		 chmod($filename,0777);
		   
		   		unlink($filename);
		   }
		   
			$this->delete($where);
		}
}
?>